const bot = require("../app");
const { UrlLink } = require("wechaty");
const path = require("path");
const { FileBox } = require("file-box");
const superagent = require("../superagent");
const config = require("../config");
const { colorRGBtoHex, colorHex } = require("../utils");
const { Message } = require("wechaty");
let roomName = ''
if (Array.isArray(config.WEBROOM)) {
    config.WEBROOM.map((item) => {
        roomName += item + '\n'
    })
}
const allKeywords = `回复序号或关键字获取对应服务
1.加群
2.毒鸡汤
3.神回复(略微开车)
4.英语一句话
5.每日一篇文章
6.舔狗日记
7.来句诗词
8.心灵鸡汤
9.土味情话
10.成语接龙(成语接龙 一叶障目 或者10 一叶障目)
转小写(例：转小写CKNIGHT)
转大写(例：转大写cknight)
转rgb(例：转rgb#cccccc)
转16进制(例：转16进制rgb(255,255,255))
天气 城市名(例：天气 上海)
全国肺炎(实时肺炎数据)
省份/自治区 肺炎(例：上海肺炎)`;
/**
 * sleep
 * @param {*} ms
 */
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
/**
 * 处理消息
 */
async function onMessage(msg) {
    //防止自己和自己对话
    if (msg.self()) return;
    const room = msg.room(); // 是否是需要管理的群消息
    // console.log(room);
    if (room) {
        //处理群消息
        if (config.WEBROOM.includes(room.payload.topic)) {
            // 只回应在配置名单里的群组
            await onWebRoomMessage(msg);
        }
    } else {
        //处理用户文字消息 
        const isText = msg.type() === Message.Type.Text;
        if (isText) {
            // const contact = msg.from();
            const contact = msg.talker();
            if (config.FOCUS.includes(contact.payload.name) || config.FOCUS.includes(contact.payload.alias)) { //只有消息发送人为config中特别关注的人才调用图灵接口
                // 先走图灵数据
                let res = await superagent.tuling(msg.text().trim(), contact.payload.name);
                if (res.intent.code === 10004 || res.intent.code === 10014) { //调用成功时,10014图片
                    if (res.intent.code === 10014) {
                        await delay(200);
                        await msg.say(res.results[1].values.text);
                        try {
                            const urlLink = new UrlLink({
                                description: res.results[1].values.text + msg.text().trim(),
                                url: res.results[0].values.url
                            })
                            await delay(200);
                            await msg.say(urlLink);
                        } catch (error) {
                            console.log(error);
                        }
                        // 根据链接抓取图片
                        // https://m.image.so.com/i?q=%E9%9E%A0%E5%A9%A7%E7%A5%8E
                        try {
                            const imgList = await superagent.getTulingImg(res.results[0].values.url.split('?')[1].split('=')[1]);
                            console.log(imgList);
                            imgList.map(async(item, index) => {
                                    let fileBox = FileBox.fromUrl(item.pic)
                                    await delay(200);
                                    msg.say(fileBox)
                                })
                                // console.log(imgList);
                        } catch (error) {
                            console.log(error);
                        }
                        // https://m.image.so.com/j?q=%E8%B5%B5%E4%B8%BD%E9%A2%96%E5%A3%81%E7%BA%B8&pn=30&sn=0&kn=0&gn=0&cn=0接口
                    } else {
                        await delay(200);
                        msg.say(`${res.results[0].values.text}`)
                    }
                } else {
                    await onPeopleMessage(msg);
                }
            } else {
                await onPeopleMessage(msg);
            }
        }
    }
};
/**
 * 处理用户消息
 */
async function onPeopleMessage(msg) {
    //获取发消息人
    // const contact = msg.from();
    const contact = msg.talker();
    //对config配置文件中ignore的用户消息不必处理
    if (config.IGNORE.includes(contact.payload.name)) return;
    let content = msg.text().trim(); // 消息内容 ，使用trim()去除前后空格
    if (content === "菜单") {
        await delay(200);
        await msg.say(allKeywords);
    } else if (content === "打赏") {
        //这里换成自己的赞赏二维码
        const fileBox = FileBox.fromFile(path.join(__dirname, "../imgs/pay.png"));
        await msg.say("我是秦始皇，打钱!!!!!");
        await delay(200);
        await msg.say(fileBox);
    } else if (
        // 如果消息为要加的群名
        config.WEBROOM.includes(content)
    ) {
        const webRoom = await bot.Room.find({
            topic: content
        });
        if (webRoom) {
            try {
                await delay(200);
                await webRoom.add(contact);
            } catch (e) {
                console.error(e);
            }
        }
    } else if (content === "加群" || content === "1") {
        if (Array.isArray(config.WEBROOM)) {
            await delay(200);
            await msg.say(`群聊列表：${roomName}\n` + '请回复想要加入的群名称（如：\n不将就的散步）');
        } else {
            const webRoom = await bot.Room.find({
                topic: content
            });
            if (webRoom) {
                try {
                    await delay(200);
                    await webRoom.add(contact);
                } catch (e) {
                    console.error(e);
                }
            }
        }
    } else if (content === "毒鸡汤" || content === "2") {
        let soup = await superagent.getSoup();
        await delay(200);
        await msg.say(soup);
    } else if (content === "神回复" || content === "3") {
        const { title, content } = await superagent.getGodReply();
        await delay(200);
        await msg.say(`标题：${title}\n\n神回复：${content}`);
    } else if (content === "英语一句话" || content === "4") {
        const { en, zh } = await superagent.getEnglishOne();
        await delay(200);
        await msg.say(`en：${en}\n\nzh：${zh}`);
    } else if (content === "每日一篇文章" || content === "5") {
        const res = await superagent.getOneAritcle();
        await delay(200);
        let content = [];
        for (let i = 0; i < (res.content.length / 5000); i++) {
            content.push(res.content.substr(i * 5000, (i + 1) * 5000))
        }
        content.forEach(async(item, index) => {
            if (index === 0) {
                await msg.say(`${res.quote}\n${res.title}\n${res.author}\n\n${item}`);
            } else {
                if (item != '') {
                    await msg.say(`${item}`);
                }
            }
        })
    } else if (content === "舔狗日记" || content === "6") {
        const { content } = await superagent.getNoHouse();
        await delay(200);
        await msg.say(content);
    } else if (content === "来句诗词" || content === "7") {
        const data = await superagent.getPoerty();
        await delay(200);
        await msg.say(`${data.content}\n${data.origin.title}     【${data.origin.author}】【${data.origin.dynasty}】\n全文：${data.origin.content}`);
    } else if (content === "心灵鸡汤" || content === "8") {
        const soup = await superagent.getHeartSoup();
        await delay(200);
        await msg.say(`${soup.hitokoto}\nfrom:${soup.from_who}`);
    } else if (content === "土味情话" || content === "9") {
        const { content } = await superagent.getLoveSay();
        await delay(200);
        await msg.say(content);
    } else if (content.findIndex("成语接龙") != -1 || content.findIndex("10") != -1) {
        if (content.split('')[1]) {
            const { content } = await superagent.chengyujielong(content.split('')[1]);
        } else {
            content = '输入格式不正确'
        }
        await delay(200);
        await msg.say(content);
    } else if (content === "客服") {
        const contactCard = await bot.Contact.find({ alias: config.MYSELF }); // change 'lijiarui' to any of the room member
        await msg.say(contactCard);
    } else {
        const noUtils = await onUtilsMessage(msg);
        if (noUtils && (!(config.FOCUS.includes(contact.payload.name) || config.FOCUS.includes(contact.payload.alias)))) {
            // await delay(200);
            // await msg.say('暂时无法理解你的话,请回复菜单，查看更多功能');
        }
    }
}
/**
 * 处理群消息
 */
// <br>无法换行，改用\n
async function onWebRoomMessage(msg) {
    const isText = msg.type() === Message.Type.Text;
    if (isText) {
        const content = msg.text().trim(); // 消息内容
        if (content === "菜单") {
            await delay(200);
            await msg.say(`回复序号或关键字获取对应服务
            1.舔狗日记
            2.毒鸡汤
            3.神回复(略微开车)
            4.英语一句话
            5.每日一篇文章
            6.来句诗词
            7.心灵鸡汤
            8.土味情话
            9.成语接龙(成语接龙 一叶障目 或者10 一叶障目)
            转小写(例：转小写CKNIGHT)
            转大写(例：转大写cknight)
            转rgb(例：转rgb#cccccc)
            转16进制(例：转16进制rgb(255,255,255))
            天气 城市名(例：天气 上海)
            全国肺炎(实时肺炎数据)
            省份/自治区 肺炎(例：上海肺炎)`);
        } else if (content === "毒鸡汤" || content === "2") {
            let poison = await superagent.getSoup();
            await delay(200);
            await msg.say(poison);
        } else if (content === "神回复" || content === "3") {
            const { title, content } = await superagent.getGodReply();
            await delay(200);
            await msg.say(`标题：${title}\n\n神回复：${content}`);
        } else if (content === "英语一句话" || content === "4") {
            const res = await superagent.getEnglishOne();
            await delay(200);
            await msg.say(`en：${res.en}\n\nzh：${res.zh}`);
        } else if (content === "每日一篇文章" || content === "5") {
            const res = await superagent.getOneAritcle();
            await delay(200);
            let content = [];
            for (let i = 0; i < (res.content.length / 5000); i++) {
                content.push(res.content.substr(i * 5000, (i + 1) * 5000))
            }
            content.forEach(async(item, index) => {
                if (index === 0) {
                    await msg.say(`${res.quote}\n${res.title}\n${res.author}\n\n${item}`);
                } else {
                    if (item != '') {
                        await msg.say(`${item}`);
                    }
                }
            })
        } else if (content === "舔狗日记" || content === "1") {
            const { content } = await superagent.getNoHouse();
            await delay(200);
            await msg.say(content);
        } else if (content === "来句诗词" || content === "6") {
            const data = await superagent.getPoerty();
            await delay(200);
            await msg.say(`${data.content}\n${data.origin.title}     【${data.origin.author}】【${data.origin.dynasty}】\n全文：${data.origin.content}`);
        } else if (content === "心灵鸡汤" || content === "7") {
            const soup = await superagent.getHeartSoup();
            await delay(200);
            await msg.say(`${soup.hitokoto}\nfrom:${soup.from_who}`);
        } else if (content === "土味情话" || content === "8") {
            const { content } = await superagent.getLoveSay();
            await delay(200);
            await msg.say(content);
        } else if (content.findIndex("成语接龙") != -1 || content.findIndex("9") != -1) {
            if (content.split('')[1]) {
                const { content } = await superagent.chengyujielong(content.split('')[1]);
            } else {
                content = '输入格式不正确'
            }
            await delay(200);
            await msg.say(content);
        } else if (content.includes("踢@")) {
            // 踢人功能  群里发送  踢@某某某  即可
            const room = msg.room();
            //获取发消息人
            // const contact = msg.from();
            const contact = msg.talker();
            const alias = await contact.alias();
            //如果是机器人好友且备注是自己的大号备注  才执行踢人操作
            if (contact.friend() && alias === config.MYSELF) {
                const delName = content.replace("踢@", "").trim();
                const delContact = await room.member({ name: delName });
                await room.del(delContact);
                await msg.say(delName + "已被移除群聊。且聊且珍惜啊！");
            }
        } else {
            await onUtilsMessage(msg);
        }
    }
}

/**
 * utils消息处理
 */
async function onUtilsMessage(msg) {
    const isText = msg.type() === Message.Type.Text;
    if (isText) {
        let content = msg.text().trim(); // 消息内容
        if (content.indexOf("转大写") === 0) {
            try {
                const str = content.replace("转大写", "").trim().toUpperCase();
                await msg.say(str);
            } catch (error) {
                await msg.say("转换失败，请检查");
            }
        } else if (content.indexOf("转小写") === 0) {
            try {
                const str = content.replace("转小写", "").trim().toLowerCase();
                await msg.say(str);
            } catch (error) {
                await msg.say("转换失败，请检查");
            }
        } else if (content.indexOf("天气") === 0) {
            const weather = await superagent.getWeather(content.split(' ')[1])
            await msg.say(`更新时间：${weather.update_time} ${weather.week}\n${weather.country}${weather.city}\n天气情况:${weather.wea}\n实时温度${weather.tem}(${weather.tem2}~${weather.tem1})
风向:${weather.win}  风力等级:${weather.win_speed}  风速:${weather.win_meter}\n湿度${weather.humidity} 能见度：${weather.visibility}\n气压hPa:${weather.pressure}\n空气质量:${weather.air}
空气质量等级:${weather.air_level}\n空气质量描述:${weather.air_tips}
            `);
        } else if (content.indexOf("转16进制") === 0) {
            try {
                const color = colorRGBtoHex(content.replace("转16进制", "").trim());
                await msg.say(color);
            } catch (error) {
                console.error(error);
                await msg.say("转换失败，请检查");
            }
        } else if (content.indexOf("转rgb") === 0) {
            try {
                const color = colorHex(content.replace("转rgb", "").trim());
                await msg.say(color);
            } catch (error) {
                console.error(error);
                await msg.say("转换失败，请检查");
            }
        } else if (content === "全国肺炎") {
            try {
                const res = await superagent.getChinaFeiyan();
                const chinaTotal = res.data.chinaTotal.total;
                const chinaToday = res.data.chinaTotal.today;
                const str = `全国新冠肺炎实时数据：\n确诊：${chinaTotal.confirm
                    }\n较昨日：${chinaToday.confirm > 0 ? "+" + chinaToday.confirm : chinaToday.confirm
                    }\n疑似：${chinaTotal.suspect}\n较昨日：${chinaToday.suspect > 0 ? "+" + chinaToday.suspect : chinaToday.suspect
                    }\n死亡：${chinaTotal.dead}\n较昨日：${chinaToday.dead > 0 ? "+" + chinaToday.dead : chinaToday.dead
                    }\n治愈：${chinaTotal.heal}\n较昨日：${chinaToday.heal > 0 ? "+" + chinaToday.heal : chinaToday.heal
                    }\n------------------\n数据采集于网易，如有问题，请及时联系`;
                msg.say(str);
            } catch (error) {
                msg.say("接口错误");
            }
        } else if (content.includes("肺炎")) {
            const config = [
                "北京",
                "湖北",
                "广东",
                "浙江",
                "河南",
                "湖南",
                "重庆",
                "安徽",
                "四川",
                "山东",
                "吉林",
                "福建",
                "江西",
                "江苏",
                "上海",
                "广西",
                "海南",
                "陕西",
                "河北",
                "黑龙江",
                "辽宁",
                "云南",
                "天津",
                "山西",
                "甘肃",
                "内蒙古",
                "台湾",
                "澳门",
                "香港",
                "贵州",
                "西藏",
                "青海",
                "新疆",
                "宁夏"
            ];
            let newContent = content.replace("肺炎", "").trim();
            if (config.includes(newContent)) {
                const data = await superagent.getProvinceFeiyan(newContent);
                let citystr = "名称  确诊  治愈  死亡\n";
                data.city.forEach(item => {
                    citystr =
                        citystr +
                        `${item.name}  ${item.conNum}  ${item.cureNum}  ${item.deathNum}\n`;
                });
                const str = `${newContent}新冠肺炎实时数据：\n确诊：${data.value}\n较昨日：${data.adddaily.conadd}\n死亡：${data.deathNum}\n较昨日：${data.adddaily.deathadd}\n治愈：${data.cureNum}\n较昨日：${data.adddaily.cureadd}\n------------------\n各地市实时数据：\n${citystr}------------------\n数据采集于新浪，如有问题，请及时联系`;
                msg.say(str);
            }
        } else {
            return true;
        }
    } else {
        return true;
    }
}
module.exports = onMessage;